package com.gjh.xiaokabang2code.async;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gjh.xiaokabang2code.common.BusinessException;
import com.gjh.xiaokabang2code.common.DesUtil;
import com.gjh.xiaokabang2code.common.ErrorCode;
import com.gjh.xiaokabang2code.common.HideCharactersUtil;
import com.gjh.xiaokabang2code.mapper.BankcardMapper;
import com.gjh.xiaokabang2code.model.Bankcard;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.gjh.xiaokabang2code.common.CustomMailSender.PREMailSendToLoser;
import static com.gjh.xiaokabang2code.service.impl.UserServiceImpl.SALT;

@Component
public class PreSendMail {
    @Resource
    private BankcardMapper bankcardMapper;
    @Async
    public void preSendMailToLoser(String bankCard) throws Exception {
        QueryWrapper<Bankcard> bankcardQueryWrapper = new QueryWrapper<>();
        bankcardQueryWrapper.eq("u_bankcard",new DesUtil(SALT).encrypt(bankCard, "CBC"));
        List<Bankcard> bankcards = bankcardMapper.selectList(bankcardQueryWrapper);
        if (bankcards.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }
        if (!bankcards.isEmpty()) {
            String uId = bankcards.get(0).getUId();
            String fourBankcard = HideCharactersUtil.convertToFourDigits(bankCard);
            String formattedDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm");
            String stuNumMail = "vm" + uId + "@jzxy.edu.cn";
            PREMailSendToLoser(stuNumMail,formattedDate,fourBankcard);
        }
    }
}
